package com.leo.apptest.utils;

import android.content.Context;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.TouchDelegate;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

/**
 * Created by ylb on 2014/11/7.
 */
public class ViewUtils {

    /**
     * 有内容就显示，没内容隐藏
     */
    public static void setTextToView(TextView tv, String content) {
        setTextToView(tv, content, content);
    }

    /**
     * 有内容就显示，没内容隐藏
     */
    public static void setTextToView(TextView tv, String condition, String content) {
        if (tv == null) {
            return;
        }
        if (TextUtils.isEmpty(condition)) {
            tv.setVisibility(View.GONE);
        } else {
            tv.setVisibility(View.VISIBLE);
            tv.setText(content);
        }
    }

    /**
     * 判断listview是否在顶部
     *
     * @param listView
     * @return
     */
    public static boolean listIsAtTop(ListView listView) {
        if (listView == null || listView.getChildCount() == 0) return true;
        return listView.getChildAt(0).getTop() == 0;
    }

    public static boolean listIsAtTop(RecyclerView recyclerView) {
        if (recyclerView == null || recyclerView.getChildCount() == 0) return true;

        if (recyclerView.getChildLayoutPosition(recyclerView.getChildAt(0)) == 0) {
            return recyclerView.getChildAt(0).getTop() == 0;
        }

        return false;
    }

    public static int getDeviceWidth(Context context) {
        return context.getResources().getDisplayMetrics().widthPixels;
    }

    public static int getDeviceHeight(Context context) {
        return context.getResources().getDisplayMetrics().heightPixels;
    }


    public  static int getViewWidth(View view){
        view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        return view.getMeasuredWidth();
    }

    public static int getViewHeight(View view){
        view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        return view.getMeasuredHeight();
    }

    public static void expandViewTouchDelegate(final View view, final int top,
                                               final int bottom, final int left, final int right) {

        ((View) view.getParent()).post(new Runnable() {
            @Override
            public void run() {
                Rect bounds = new Rect();
                view.setEnabled(true);
                view.getHitRect(bounds);

                bounds.top -= top;
                bounds.bottom += bottom;
                bounds.left -= left;
                bounds.right += right;

                TouchDelegate touchDelegate = new TouchDelegate(bounds, view);

                if (View.class.isInstance(view.getParent())) {
                    ((View) view.getParent()).setTouchDelegate(touchDelegate);
                }
            }
        });
    }

}
